import { useStore } from '@/hooks';
import { Button, Dialog, Form } from '@alifd/next';
import { observable } from 'mobx';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid } from '../stores/definitions';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { observer } from 'mobx-react-lite';

const FromItem = Form.Item;
const formItemLayout = {
  labelCol: {
    fixedSpan: 8,
  },
  wrapperCol: {
    span: 14,
  },
  style: { marginBottom: 20 },
};

const RegionForm = ({ regionId, parentId, modal, onSubmit, onCancel }) => {
  const { portStore: store } = useStore();
  const [isViewMode] = useState(modal[0] === 'view');
  const formProps = isViewMode ? { field: false } : {};
  const [region] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      if (regionId) {
        const data = await store.get(regionId);
        editCtx.origin = _.cloneDeep(data);
        _.assign(region, { ...data, disabled: !data.disabled });
      } else {
        // 添加操作
        const nextId = await store.nextId(parentId);
        // eslint-disable-next-line @iceworks/best-practices/recommend-polyfill
        _.set(region, 'itemId', `${(`${nextId}`).padStart(3, '0')}`); // 这里是编号生成规则
        _.set(region, 'sortWeight', 1);
      }
    })();
  }, []);

  if (!region) return <></>;

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(region, name, value);
    // 联动效果可以在这里通过设置region属性实现

    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
    // console.log('form data: ', name, value, toJS(region));
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-param-reassign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => { v !== undefined && (r[k] = v); }))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleSubmit = (value, errors, _field) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: PortForm.jsx:164 _ errors:', errors);
      return;
    }
    _.set(region, 'disabled', !region.disabled);
    onSubmit?.(region);
  };

  return (
    <Form
      isPreview={isViewMode}
      {...formProps}
      value={region}
      colon
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <FieldsGrid
        formData={region}
        itemLayout={{ ...formItemLayout, labelAlign: 'left' }}
        mode={modal[0]}
        columns={1}
        fields={((modal[0] === 'add' || isViewMode) ? ['itemId'] : []).concat(['name', 'sortWeight', 'disabled', 'description'])}
      />
      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
};

export default observer(RegionForm);
